<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>登录 - Passkey</title>
</head>
<body>
<h2>使用 Passkey 登录</h2>

<button onclick="login()">登录</button>
<pre id="log"></pre>

<script>
    const log = msg => {
      document.getElementById('log').textContent += `${msg}\n`;
    };

    function base64urlToBase64(base64url) {
      base64url = base64url
        .replace(/-/g, '+')
        .replace(/_/g, '/');
      // 补齐 =
      while (base64url.length % 4) {
        base64url += '=';
      }
      return base64url;
    }

    const decode = b64url => {
          const base64 = base64urlToBase64(b64url);
          return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
        };
    const encode = buf => {
      const base64 = btoa(String.fromCharCode(...new Uint8Array(buf)));
      return base64ToBase64Url(base64);
    };
    function base64ToBase64Url(base64) {
      return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }

    const getToken = () => {
      return '1'; // 从cookie或sessionStorage中获取token
    };

    async function login() {
      const token = getToken();
      if (!token) {
        log('❌ 未找到 token，请登录后再试。');
        return;
      }
        const url = `/passkey/login/options?unionId=`+token;

      log('请求身份验证选项...');
      const res = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!res.ok) {
        log('❌ 获取身份验证选项失败');
        return;
      }

      const options = await res.json();
      const option = options.data;

      option.challenge = decode(option.challenge);
      delete option.extensions;
      console.log(option);

      // 使用WebAuthn API进行登录
      const cred = await navigator.credentials.get({
        publicKey: {
          challenge: option.challenge,
          timeout: option.timeout,  // 超时时间
          rpId: option.rpId,  // RP ID
          extensions: option.extensions || {}  // 扩展
        }
      });

      const response = {
        id: cred.id,
        unionId:token,
        rawId: encode(cred.rawId),
        type: cred.type,
        response: {
          clientDataJSON: encode(cred.response.clientDataJSON),
          authenticatorData: encode(cred.response.authenticatorData),
          signature: encode(cred.response.signature),
          userHandle: cred.response.userHandle ? encode(cred.response.userHandle) : null
        }
      };

      const request = JSON.stringify(response);
      console.log(request, "ssss");

      log('发送登录请求...');
      const verifyRes = await fetch('/passkey/login/complete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: request
      });

      const result = await verifyRes.json();
      log('登录结果: ' + JSON.stringify(result));
    }
</script>
</body>
</html>
